package com.yasha.control;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.Paint.Join;
import android.util.Log;

import com.yasha.model.HttpValues;
import com.yasha.model.News;
import com.yasha.ulti.Const;
import com.yasha.ulti.JSONParser;
import com.yasha.ulti.Tools;

public class NewsController {
	private String TAG = "NewsController";
	private JSONParser jParser = new JSONParser();
	private JSONObject data = null;

	public boolean addNewsToServer(News news) {
		Log.d(TAG, "UPLOAD: SendMultipartFile");
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Const.AddNewsToServer);

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		/* example for setting a HttpMultipartMode */
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		/* example for adding an image part */

		builder.addPart("userName", new StringBody(news.getUsername(),
				ContentType.DEFAULT_TEXT));
		builder.addPart("lat", new StringBody(news.getLati() + "",
				ContentType.DEFAULT_TEXT));
		builder.addPart("lng", new StringBody(news.getLongti() + "",
				ContentType.DEFAULT_TEXT));
		builder.addPart("city", new StringBody(news.getCity(),
				ContentType.DEFAULT_TEXT));
		builder.addPart("newsTitle", new StringBody(news.getTitle(),
				ContentType.DEFAULT_TEXT));
		builder.addPart("newsContent", new StringBody(news.getContent(),
				ContentType.DEFAULT_TEXT));
		builder.addPart("updateDate", new StringBody(news.getUpdateDate(),
				ContentType.DEFAULT_TEXT));
		builder.addPart("validDate", new StringBody(news.getValiDate(),
				ContentType.DEFAULT_TEXT));
		builder.addPart("imgFolderLink", new StringBody(news.getImgFolder(),
				ContentType.DEFAULT_TEXT));
		builder.addPart("topic", new StringBody(news.getTopic(),
				ContentType.DEFAULT_TEXT));

		File file = new File(news.getImgs()[0]);
		if (file.exists()) {
			FileBody fileBody = new FileBody(file); // image should be a String
			builder.addPart("userfile", fileBody);
		}
		// StringBody a=new StringBody("aaa", Charset.);
		// and so on

		httppost.setEntity(builder.build());
		Log.d(TAG, "UPLOAD: executing request: " + httppost.getRequestLine());
		Log.d(TAG, "UPLOAD: request: "
				+ httppost.getEntity().getContentType().toString());

		HttpResponse response;
		try {
			Log.d(TAG, "UPLOAD: about to execute");
			response = httpclient.execute(httppost);
			Log.d(TAG, "UPLOAD: executed");
			HttpEntity resEntity = response.getEntity();
			Log.d(TAG, "UPLOAD: respose code: "
					+ response.getStatusLine().toString());
			String responseString = "";
			if (resEntity != null) {
				responseString = EntityUtils.toString(resEntity);
				Log.d(TAG, "UPLOAD: " + responseString);
				data = new JSONObject(responseString);
				String status = data.getString("status");
				if (status.equals("fail")) {
					data = null;
					return false;
				}
			}
			if (resEntity != null) {
				resEntity.consumeContent();
			}

		} catch (Exception e) {
			e.printStackTrace();
			data = null;
			return false;
		}

		return true;
	}

	public ArrayList<News> getNewsForServer(String topic, String city) {
		ArrayList<News> results = new ArrayList<News>();

		Tools.Log(TAG, " getNewsForServer : " + topic + "city : " + city);
		try {
			ArrayList<HttpValues> data = new ArrayList<HttpValues>();

			JSONObject jObj;
			if (!city.equals("") && !topic.equals("")) {
				data.add(new HttpValues("city", city));
				data.add(new HttpValues("topic", topic));
				jObj = jParser
						.getJSONFromUrl(Const.getNewsByTopicAndCity, data);
				
				Tools.Log(TAG, " getNewsForServer both");
			} else if (city.equals("") && !topic.equals("")) {
				data.add(new HttpValues("topic", topic));
				jObj = jParser.getJSONFromUrl(Const.getNewsByTopic, data);
				
				Tools.Log(TAG, " getNewsForServer topic");
			} else {
				data.add(new HttpValues("city", city));
				jObj = jParser.getJSONFromUrl(Const.getNewsByCity, data);
				
				Tools.Log(TAG, " getNewsForServer city");
			}
			String status = jObj.getString("status").trim();
			if (status.equals("success")) {
				JSONArray newss = jObj.getJSONArray("newss");
				for (int i = 0; i < newss.length(); i++) {
					String[] array = {};
					JSONObject dataNews = newss.getJSONObject(i);
					News news = new News(dataNews.getInt("id"),
							dataNews.getString("userCode"),
							dataNews.getString("newsContent"),
							dataNews.getString("newsTitle"),
							dataNews.getString("topic"),
							dataNews.getString("city"), "phone",
							(float) dataNews.getDouble("lng"),
							(float) dataNews.getDouble("lat"),
							dataNews.getString("updateDate"),
							dataNews.getString("validDate"),
							dataNews.getString("imgFolderLink"), array);
					results.add(news);
				}
			}
		} catch (Exception e) {
			Tools.Log(TAG, " addUserToServer error: " + e.toString());
		}

		return results;
	}
	
	
}
